Skip to main content

Data Types

Resources

1. Data Types

Primitive Types (7):
  1. [[03. Numbers|numbers]]
  2. bigint (added more recently)
  3. [[04. String Methods|string]]
  4. boolean
  5. null
  6. undefined
  7. symbol (added in ES6)

Non-Primitive/Reference Type (1): 8. [[11. Objects|object]]

  • This includes:
    • Plain objects {}
    • Arrays
    • Functions
    • Dates
    • Custom class instances

0. The typeof operator

The typeof operator returns the type of the operand. It’s useful when we want to process values of different types differently or just want to do a quick check. We can better see the use of typeof in the following sections.

typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object" (1)

typeof null // "object" (2)

typeof alert // "function" (3)

1. Number

  • The number type represents both integer and floating point numbers.
  • There are many [[03. Numbers#1. Arithmetic Operations |arithmetic operations]] for numbers, e.g. multiplication *, division /, addition +, subtraction -, and so on.
  • Besides regular numbers, there are so-called “special numeric values” which also belong to this data type: Infinity-Infinity and NaN.
let n = 123; 
n = 12.345;
console.log(typeof(n)); // Output: number
  • The Number() function converts anything passed to it into a number if it can. Try the following:
const myString = "123";
const myNum = Number(myString);
console.log(typeof myNum); // Ouput: number

2. BigInt

In JavaScript, the “number” type cannot safely represent integer values larger than $(2^53- 1)$(that’s 9007199254740991), or less than $-(2^53- 1)$ for negatives. If they do, there may be precision error. → We can use type BigInt to help store these large values, though they are rarely needed.

  • We can declare a BigInt by appending n to the end of an integer.
const bigInt = 1234567890123456789012345678901234567890n;
console.log(typeof(bigInt)); // Output: bigint

3. Strings

Resources

Note: There are no character char type in JavaScript.

  1. string is a piece of text and is declared with surrounding quotes. There are three types of quotes we can use to surround a string in JavaScript:
  • Double quote: "Hello"
  • Single quote: 'Hello'
  • Backticks: ``Hello

Double and single quotes are “simple” quotes. There’s practically no difference between them in JavaScript.

let userName = "My Name"; 
console.log(typeof(userName)); // Output: string
  1. String Literals: we use backticks and ${...} to embed variables and expressions into a string. ^5ba1e5
  • The expression inside ${…} is evaluated and the result becomes a part of the string. We can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more complex.
let userName = "My Name";
console.log(`Hello, my name is: ${userName}!`)
// Output: Hello, my name is My Name!
  • Using template literals, we can include expressions in strings:
const song = "Hello World";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
(score / highestScore) * 100
}%.`;
console.log(output); // Output: "I like the song Hello World. I gave it a score of 90%."
  1. JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it.
let myString = "Hello!"
myString[0] = "Y"; // We're trying to turn this string into "Yello";
// but this will cause an error
  1. [[03. Numbers#3. Adding Numbers and Strings - + Operator|String Concatenation]]: We can concatenate normal strings using the + operator:
const greeting = "Hello";
const name = "User1";
console.log(greeting + ", " + name); // "Hello, User1"

→ However, template [[#^5ba1e5|literals]] usually give you more readable code.

4. Boolean

The boolean type has only two values: true and false. This type is commonly used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”.

let greaterThanOne = true; 
let greaterThanTen = false;
console.log(typeof(greaterThanOne)) // Output:

Boolean values also come as a result of comparisons:

let isGreater = 4 > 1; 
console.log(isGreater); // Output: true;

5. null value

The special null value does not belong to any of the types described above. It forms a separate type of its own which contains only the null value. It’s just a special value which represents “nothing”, “empty” or “value unknown”.

let age = null; // age is unknown
console.log(typeof(age)); // Output: object - because null is an object in JavaScript

6. undefined value

The special value undefined also stands apart. It makes a type of its own, just like null. The meaning of undefined is “value is not assigned”.

  • If a variable is declared, but not assigned, then its value is undefined.
let x; 
console.log(typeof(x)); // Output: undefined

7. Symbols

symbol is a unique and immutable primitive value and may be used as the key of an Object property.

8. [[11. Objects|Objects]]

The object type is special. All other types are called “primitive” because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities.

Arrays in JavaScript, though best described as arrays, is also considered a type of objects.

let user = { // an object called user
name: "John", // the key "name" store value "John"
age: 30 // the key "age" store value 30
};

console.log(typeof (user)); // Output: object

const students = ["Annie", "Ben", "Cam"];
console.log(typeof(students)); // Output: object

2. Type Semantics

In this example, for primitive types, the function receives a copy of the value. With the non-primitive, the function receives a reference to the original object, so modifications affect the original data.

// Primitive type (passed by value)
let originalNumber = 5;
function changePrimitive(num) {
num = 10; // This doesn't affect the original value
}
changePrimitive(originalNumber);
console.log(originalNumber); // Still 5

// Non-primitive type (passed by reference)
let originalArray = [1, 2, 3];
function changeArray(arr) {
arr.push(4); // This modifies the original array
}
changeArray(originalArray);
console.log(originalArray); // Now [1, 2, 3, 4]

// Object example
let originalObject = { x: 1 };
function changeObject(obj) {
obj.x = 2; // This modifies the original object
}
changeObject(originalObject);
console.log(originalObject); // { x: 2 }

With primitives, you get a copy; with non-primitives, you get a reference that can be directly modified.